﻿using DevExpress.XtraEditors;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Equipment.Select;
using MesProjectWinform.Public;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Equipment.Form.ProjectFrom
{
    /// <summary>
    /// 修改项目表单
    /// </summary>
    public partial class ProjectFromEditForm : DevExpress.XtraEditors.XtraForm
    {
        public ProjectFromEditForm()
        {
            InitializeComponent();
        }
        // 添加这个字段来存储选中的项目维护ID
        private List<long> selectedProjectMaintenanceIds = new List<long>();

        /// <summary>
        /// 项目表单编号
        /// </summary>
        private long Id { get; set; }

        /// <summary>
        /// 回显数据
        /// </summary>
        public void GetProjectFromData(ProjectFromOutput projectFromOutput)
        {
            Id = projectFromOutput.Id;
            ProjectName.Text = projectFromOutput.ProjectName;
            ProjectDescription.Text = projectFromOutput.ProjectDescription;
            // 首先确保下拉框数据已加载
            LoadSeelct();

            // 回显项目类型下拉框 - 关键修改部分
            if (!string.IsNullOrEmpty(projectFromOutput.ProjectType))
            {
                Console.WriteLine($"要回显的项目类型值: {projectFromOutput.ProjectType}"); // 调试信息

                var projectTypeList = ProjectType.Properties.DataSource as List<ProjectTypeOutput>;
                if (projectTypeList != null)
                {
                    // 调试信息：输出数据源中的所有项
                    foreach (var item in projectTypeList)
                    {
                        Console.WriteLine($"数据源项: Id={item.Id}, Name={item.ProjectTypeName}");
                    }

                    // 尝试通过名称匹配
                    var matchByName = projectTypeList.FirstOrDefault(pt =>
                        pt.ProjectTypeName.Equals(projectFromOutput.ProjectType, StringComparison.OrdinalIgnoreCase));

                    if (matchByName != null)
                    {
                        Console.WriteLine($"通过名称找到匹配项: Id={matchByName.Id}");
                        ProjectType.EditValue = matchByName.Id;
                    }
                    else
                    {
                        // 如果ProjectType存储的是"点检"或"保养"这样的文本
                        // 我们需要手动查找对应的ID
                        switch (projectFromOutput.ProjectType.Trim().ToLower())
                        {
                            case "点检":
                                ProjectType.EditValue = 1;
                                break;
                            case "保养":
                                ProjectType.EditValue = 2;
                                break;
                            default:
                                // 如果是数字，可能直接是ID
                                if (int.TryParse(projectFromOutput.ProjectType, out int typeId))
                                {
                                    ProjectType.EditValue = typeId;
                                }
                                break;
                        }
                    }

                    // 检查设置后的值
                    Console.WriteLine($"设置后的EditValue: {ProjectType.EditValue}, Text: {ProjectType.Text}");
                }
            }

            if (!string.IsNullOrEmpty(projectFromOutput.ProjectMaintenanceNames))
            {
                ProjectMaintenanceId.Text = projectFromOutput.ProjectMaintenanceNames;
            }

            // 2. 保存项目维护ID列表，用于后续保存操作
            if (projectFromOutput.ProjectMaintenanceIds != null && projectFromOutput.ProjectMaintenanceIds.Count > 0)
            {
                selectedProjectMaintenanceIds = new List<long>(projectFromOutput.ProjectMaintenanceIds);
                Console.WriteLine($"已加载项目维护ID: {string.Join(",", selectedProjectMaintenanceIds)}");
            }
            // 3. 如果没有ID列表但有名称，可能需要通过API获取对应的ID
            else if (!string.IsNullOrEmpty(projectFromOutput.ProjectMaintenanceNames) &&
                    (selectedProjectMaintenanceIds == null || selectedProjectMaintenanceIds.Count == 0))
            {
                // 这种情况可能需要通过API查询项目维护名称对应的ID
                // 可以在这里添加异步调用，或者在编辑保存时处理
                Console.WriteLine("警告: 有项目维护名称但没有对应的ID列表");
            }
        }

        /// <summary>
        /// 项目表单类型下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProjectFromEditForm_Load(object sender, EventArgs e)
        {
            LoadSeelct();
        }

        /// <summary>
        /// 加载项目表单检验方式
        /// </summary>
        private void LoadSeelct()
        {
            try
            {
                #region  加载项目类型下拉框
                List<ProjectTypeOutput> projectTypeOutputs = new List<ProjectTypeOutput>()
                {
                    new ProjectTypeOutput()
                    {
                        Id = 1,
                        ProjectTypeName = "点检"
                    },
                    new ProjectTypeOutput()
                    {
                        Id = 2,
                        ProjectTypeName = "保养"
                    },
                };

                // 设置数据源
                ProjectType.Properties.DataSource = projectTypeOutputs;

                // 关键修改：明确设置DisplayMember和ValueMember
                ProjectType.Properties.DisplayMember = "ProjectTypeName";
                ProjectType.Properties.ValueMember = "Id";  // 确保设置了ValueMember

                // 设置下拉列表的列
                ProjectType.Properties.Columns.Clear();
                ProjectType.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("ProjectTypeName", "类型名称"));

                ProjectType.Properties.NullText = "请选择项目表单类型";

                // 调试信息
                Console.WriteLine("项目类型下拉框数据源已加载");
                #endregion
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载下拉框数据出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"加载下拉框异常: {ex.Message}\n{ex.StackTrace}");
            }
        }


        /// <summary>
        /// 关闭按钮点击时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ColseButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 选择按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectButton3_Click(object sender, EventArgs e)
        {
            // 创建项目维护选择窗体
            ProjectMaintenanceSelectForm projectMaintenanceSelectForm = new ProjectMaintenanceSelectForm();

            // 注册选择完成事件处理程序
            projectMaintenanceSelectForm.OnProjectMaintenanceSelected += ProjectMaintenanceSelectForm_OnProjectMaintenanceSelected;

            // 显示窗体
            projectMaintenanceSelectForm.ShowDialog();
        }

        /// <summary>
        /// 处理从ProjectMaintenanceSelectForm返回的选中数据
        /// </summary>
        /// <param name="selectedItems">选中的项目维护数据列表</param>
        private void ProjectMaintenanceSelectForm_OnProjectMaintenanceSelected(List<ProjectMaintenanceOutput> selectedItems)
        {
            if (selectedItems != null && selectedItems.Count > 0)
            {
                // 清空之前存储的ID列表
                selectedProjectMaintenanceIds.Clear();

                // 将选中项目的名称以逗号分隔拼接起来
                string selectedNames = string.Join(",", selectedItems.Select(item => item.ProjectMaintenanceName));

                // 收集所有选中项目的ID
                foreach (var item in selectedItems)
                {
                    selectedProjectMaintenanceIds.Add(item.Id);
                }

                // 设置到检验项目输入框中
                ProjectMaintenanceId.Text = selectedNames;
            }
        }

        /// <summary>
        /// 保存点击按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void UpdateProjectFromButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 1. 数据验证
                // 名称非空验证
                if (string.IsNullOrWhiteSpace(ProjectName.Text))
                {
                    XtraMessageBox.Show("项目表单名称不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectName.Focus();
                    return;
                }

                // 名称长度验证
                if (ProjectName.Text.Length > 30)
                {
                    XtraMessageBox.Show("项目表单名称不能超过30个字符", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectName.Focus();
                    return;
                }

                // 项目类型非空验证
                if (ProjectType.EditValue == null)
                {
                    XtraMessageBox.Show("请选择项目表单类型", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectType.Focus();
                    return;
                }

                // 检验项目非空验证
                if (string.IsNullOrWhiteSpace(ProjectMaintenanceId.Text))
                {
                    XtraMessageBox.Show("请选择检验项目", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceId.Focus();
                    return;
                }

                // 描述长度验证
                if (ProjectDescription.Text.Length > 100)
                {
                    XtraMessageBox.Show("项目表单描述不能超过100个字符", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectDescription.Focus();
                    return;
                }

                // 2. 创建更新对象
                ProjectFromOutput projectFromOutput = new ProjectFromOutput
                {
                    Id = this.Id, // 确保有正确的ID
                    ProjectName = ProjectName.Text.Trim(),
                    ProjectType = ProjectType.Text.Trim(),
                    ProjectDescription = ProjectDescription.Text.Trim(),
                    // 设置项目维护ID列表
                    ProjectMaintenanceIds = selectedProjectMaintenanceIds != null && selectedProjectMaintenanceIds.Count > 0
                        ? selectedProjectMaintenanceIds
                        : new List<long>(),
                    // 设置项目维护名称
                    ProjectMaintenanceNames = ProjectMaintenanceId.Text.Trim(),
                    UpdatedBy = "admin", // 可以从登录用户获取
                    UpdatedTime = DateTime.Now
                };

                // 3. 显示等待光标
                Cursor = Cursors.WaitCursor;

                // 4. 调用API更新数据
                using (var client = new HttpClient())
                {
                    // 序列化对象为JSON
                    var json = JsonConvert.SerializeObject(projectFromOutput);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 调用API
                    var response = await client.PutAsync("http://47.110.243.157:5229/api/ProjectForm/UpdateProjectForm", content);

                    // 处理响应
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        var responseContent = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult<bool>>(responseContent);

                        if (result != null && result.Code==ApiEnums.Success)
                        {
                            XtraMessageBox.Show("修改成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            // 设置对话框结果为OK，以便调用方知道更新成功
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                        else
                        {
                            // API返回成功但业务逻辑失败
                            string errorMessage = result != null ? result.Message : "未知错误";
                            XtraMessageBox.Show($"修改失败: {errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        // API调用失败
                        string errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"修改失败: {response.ReasonPhrase}\n{errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                // 异常处理
                XtraMessageBox.Show($"操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"保存异常: {ex.Message}\n{ex.StackTrace}");
            }
            finally
            {
                // 恢复默认光标
                Cursor = Cursors.Default;
            }
        }
    }
}